/**
 * Created by Ysssssss on 2021/4/28.
 */

import React, { PureComponent } from 'react'
import { Form } from "antd";
import ShoppingMallSettings from "@components/shoppingMall/ShoppingMallSettings";
import {connect} from "react-redux";
import {
    getShoppingMallSettings,
    editShoppingMallSettings
} from "@sagas/shoppingMall/shoppingMallSettings";
import notify from "@utils/tip";


@connect(({ shoppingMallSettings }) => ({
    shoppingMallSettings: shoppingMallSettings.shoppingMallSettings,

}), {
    getShoppingMallSettings,
    editShoppingMallSettings
})
class ShoppingMallSettingsPage extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            renderReady: false
        }
        this.submitTimeout = null
    }

    componentDidMount () {
        this.props.getShoppingMallSettings(() => {
            this.setState({
                renderReady: true
            })
        })
    }

    componentWillUnmount () {
        if(this.submitTimeout) {
            clearTimeout(this.submitTimeout)
            this.submitTimeout = null
        }
    }

    submitForm(changedValues, allValues) {
        if(this.submitTimeout) {
            clearTimeout(this.submitTimeout)
            this.submitTimeout = null
        }
        const { stores, ...values } = allValues
        this.submitTimeout = setTimeout(() => {
            this.props.editShoppingMallSettings({
                ...values,
                storeIds: stores.map(store => store.store_id)
            }, () => {
                notify('保存成功', 'success')
            })
        }, 1000)
    }


    render () {
        const { renderReady } = this.state
        const { shoppingMallSettings } = this.props
        const { operation_mode, stores, ...settings } = shoppingMallSettings
        return renderReady ? (
            <Form
                ref={this.formRef}
                name="store-edit"
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 20 }}
                initialValues={{
                    ...settings,
                    stores: (stores || []).map(store => ({
                        store_id: store.id,
                        store_name: store.name
                    }))
                }}
                requiredMark={false}
                onValuesChange={this.submitForm.bind(this)}
                scrollToFirstError={{
                    behavior: actions =>
                        actions.forEach(({ el, top, left }) => {
                            el.scrollTop = top - 100
                            el.scrollLeft = left
                        }),
                }}
            >
                <ShoppingMallSettings bizType={operation_mode}/>
            </Form>
        ) : null
    }
}

export default ShoppingMallSettingsPage